<template>
  <div style="display: flex">
    <div style="width:260px">
      <searchGroud @treeSelectEmit="handleTreeSelect"></searchGroud>

    </div>
  <div  style="calc( 100% - 260px );margin-left:20px;margin-top:10px;margin-right:12px;background:#fff;padding:12px;">
      <BasicForm @register="registerForm" style=" width:500px">
          <template #timePeriodSlot="{ model, field }">
            <a-select  v-model:value="model[field]" @change="timePeriodChange" :options="tpoptions"></a-select>
          </template>
          <template #timeRangSlot="{ model, field }">
            <a-range-picker style="height:32px;"  :disabled-date="disabledDate" v-model:value="rangeTime" @change="rangeTimeChange" valueFormat="YYYY-MM-DD" />
          </template>
      </BasicForm>  
      <!-- <a-button type="primary" @click="handleSchedule" preIcon="ant-design:plus-outlined">批量排班</a-button> -->
      <div class="box" style="height:500px">
        <h3></h3>
        <a-calendar
          :fullscreen="false"
          v-model:value="date"
          @panelChange="onPanelChange"
          @select="selectDate"  mode="month"
        >
          <template slot="headerRender">
            <div>
              <div class="calendar_select">
                <div class="calendar_s_select">
                </div>
              </div>
            </div>
          </template>
          <template #dateFullCellRender="{ current: value }">
            <div :class="getDateCss(value)" >
              {{ value.date() }}<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <!-- {{getTargetName(value)}} -->
              <!-- <span class="red">{{timePeriodText}}</span>  -->
              <span class="red">{{handleValidate(value)}}</span> 
            </div>
          </template>
        </a-calendar>
        <div class="buttonRow">
            <a-button type="primary" @click="handleSubmit">保存</a-button>
        </div>
      </div>
  </div>
  </div>

  <br>
  <br>
      <div style="display:flex; ">
        <!-- <BasicForm @register="registerForm" style=" width:500px"/> -->
      </div>

      <!-- <div class="box" style="margin: 0 auto;width:896px;border:1px solid #000;height:500px">
        <h3></h3>
        <a-calendar
          :fullscreen="false"
          v-model:value="date"
          @panelChange="onPanelChange"
          @select="selectDate"
        >
          <template slot="headerRender">
            <div>
              <div class="calendar_select">
                <div class="calendar_s_select">
                </div>
              </div>
            </div>
          </template>
          <template #dateFullCellRender="{ current: value }">
            <div :class="getDateCss(value)" v-on:click="showM(value)">
              {{ value.date() }}<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{getTargetName(value)}}
            </div>
          </template>
        </a-calendar>
      </div> -->
 <!-- <AttScheduleModalHand @register="register1" @success="handleSuccess"></AttScheduleModalHand> -->
    <AttManualScheduleModal @register="registerModal" @success="handleSuccess"></AttManualScheduleModal>

</template>

<script lang="ts" setup>
    import {ref, computed, unref,reactive,onMounted} from 'vue';
    import dayjs from "dayjs";
    import {BasicModal, useModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, FormSchema, useForm} from '/@/components/Form/index';
    // import AttScheduleList from './AttScheduleList.vue'
    // import AttScheduleModalHand from './components/AttScheduleModalHand.vue'
    import AttManualScheduleModal from './components/AttManualScheduleModal.vue'
    import searchGroud from './components/searchGroud.vue'
    // import searchDepart from "/@/views/baseinfo/components/searchDepart.vue"

    import {autoSchedule, saveOrUpdate,list as listSchedule,scheduleTree,attScheduleSubmit} from './AttSchedule.api';
    import {list as listRule} from '/@/views/attendance/attruledeptrelation/AttRuleDeptRelation.api';
    import {list as listTimePeriod} from '/@/views/attendance/timeperiod/AttTimePeriod.api'
    import {list as listGroup} from '/@/views/baseinfo/persongroup/SsPersonGroup.api'

    const [registerModal, {openModal}] = useModal();


    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);

    const holidays = reactive([]);

    const tpoptions = reactive([]);
    const goptions = reactive([]);

    const  groupId = ref('');
    let timePeriodText = ref('')
    let rangeTime = ref([])
    
    let sdate = ref('')
    let edate = ref('')
  rangeTime.value.push()
  sdate.value = getMonthFirst()
  edate.value = getMonthLast()
  console.log(edate.value);
  rangeTime.value = [(sdate.value)  ,(edate.value)]
    const formSchema: FormSchema[] = [
      // {
      //   label: '选择部门',
      //   field: 'departmentId',
      //   component: 'JSelectDept',
      //   componentProps: ({formModel}) => {
      //     return {
      //     checkStrictly:true,
      //     multiple:false,
      //     onChange:async (e)=>{
      //         console.log(e);
      //       goptions.splice(0, goptions.length)
      //       tpoptions.splice(0, tpoptions.length)
      //         if(e.length==0) {
      //           return;
      //         }

      //       let re = await listRule({departmentId:e[0],delFlag:"0",status:1});
      //       console.log(re);
      //       if(re?.records?.length>0) {
      //         let re1 = await listTimePeriod({ruleId: re.records[0].attRuleId});
      //         console.log(re1);

      //         for(let i = 0;i<re1.records.length;i++){
      //           let option = {};
      //           option.value = re1.records[i].id;
      //           option.label = re1.records[i].name;
      //           tpoptions.push(option);
      //         }
      //         console.log(formModel)
      //       }
      //       let re3 = await listGroup({departmentId:e[0]});
      //       if(re3?.records?.length>0){
      //         console.log(re3)

      //         for(let i = 0;i<re3.records.length;i++){
      //           let option = {};
      //           option.value=re3.records[i].id;
      //           option.label = re3.records[i].name;
      //           goptions.push(option);
      //         }
      //       }

      //     }
      // }
      //   },
      //   dynamicRules: ({model,schema}) => {
      //     return [
      //       { required: true, message: '请选择部门!'},
      //     ];
      //   },
      // },
      
      {
        label: '选择人员',
        field: 'personIds',
        required: false,
        component: 'JSelectPerson',
        componentProps: {
        showButton:false,
          labelKey: 'name',
          placeholder:'请选择人员，不先按分组排',
          params: {groupId:groupId}
        },
      },
      {
        label: '时段',
        field: 'timePeriodId',
        component: 'Select',
        // componentProps:{
        //   options:tpoptions,
        //   // onchange: (e)=>{
        //   //   console.log(e);

        //   // }
        // },
        slot:'timePeriodSlot',
        dynamicRules: ({model,schema}) => {
              return [
                    { required: true, message: '请选择时段!'},
              ];
        },
      },
      {
        label: '是否覆盖已排班',
        field: 'autorewrite',
        component: 'RadioButtonGroup',
        componentProps:{
          options:[
            {
              label: '否',
              value :false
            },
            {
              label: '是',
              value :true
            },
          ],
        },
        defaultValue: false
      },
      {
        label: '设置区间',
        field: 'timeRang',
        component: 'RadioButtonGroup',
        componentProps:{
        },
        slot:'timeRangSlot'
      },
    
    ];

    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
    //表单赋值
    // const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    //   setModalProps({confirmLoading: false,showCancelBtn:false,showOkBtn:false});
    // });
    function disabledDate(current){
      const today = new Date();
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      return current && current < yesterday;
    }

    function getGroupId() {
      return 5;
    }

    function handleSchedule(){
      openModal(true, {
       record:{
        departmentId: departmentId.value,
       },
       isUpdate: true,
       showFooter: true,
     });
    }

    function rangeTimeChange(e){
      console.log(e);
      sdate.value = e[0]
      edate.value = e[1]
      console.log(sdate.value);
      console.log(edate.value);
  }

    async function handleTreeSelect(e){
      let value = e[0]
      console.log(value);
      console.log();
      let tempArr = value.split('#')
     
      departmentId.value = tempArr[0]
      if(tempArr.length==2){
        groupId.value = tempArr[1]
      }

      await setFieldsValue({
        timePeriodId : '',
        personIds:''
      })
      
      tpoptions.splice(0, tpoptions.length)
      let re = await listRule({departmentId: departmentId.value,delFlag:"0",status:1});
      if(re?.records?.length>0) {
        let re1 = await listTimePeriod({ruleId: re.records[0].attRuleId});
        console.log(re1);
        let arr = []
        for(let i = 0;i<re1.records.length;i++){
          let option = {};
          option.value = re1.records[i].id;
          option.label = re1.records[i].name;
          tpoptions.push(option);
        }
      }
    }

    async function handleSubmit (){
        let values = await validate();
        console.log(values);
        values.sdate = sdate.value
        values.edate = edate.value
        values.groupId = groupId.value
        attScheduleSubmit(values).then(res=>{
          
        })
    }

    function timePeriodChange(e) {
      console.log(e);
      console.log(tpoptions);
      tpoptions.forEach(item=>{
        if(item.value==e){
            timePeriodText.value = item.label
        }
      })
      console.log( timePeriodText.value);
    }

    function getDateArr(){
      scheduleTree()
    }

    // const getDateCss = val=> {
    //   let _className = "";
    //   holidays.forEach((e, i) => {
    //     if ( e.holiday == val.format("YYYY-MM-DD")) {
    //       _className = "date work";
    //       return;
    //     }
    //   });
    //   return _className;
    // }

    const containTarget = val=>{
      let bl = false;
      holidays.forEach((e, i) => {
        if ( e.holiday == val.format("YYYY-MM-DD")) {
          bl =  true;
        }
      });
      return bl;
    }
    const getTarget = val=>{
      let bl = null;
      holidays.forEach((e, i) => {
        if ( e.holiday == val.format("YYYY-MM-DD")) {
          bl =  e;
        }
      });
      return bl;
    }
    const getTargetName = val=>{
      let bl = "";
      holidays.forEach((e, i) => {
        if ( e.holiday == val.format("YYYY-MM-DD")) {
          bl =  e.name;
        }
      });
      return bl;
    }

    const handleValidate = val=>{
      console.log(val.format("YYYY-MM-DD"));
      let tempVal = val.format("YYYY-MM-DD")
      let text = ''
      function isDateInRange(dateToCheck, startDate, endDate) {
          return  new Date(dateToCheck) >= new Date(startDate) && new Date(dateToCheck) <= new Date(endDate);
        }
      let bool =  isDateInRange(tempVal,sdate.value,edate.value)
        if(bool){
          text = timePeriodText.value
        }else{
          text = ''
        }

      return text
    }

    const getDateCss = val=> {
      let _className = "";
      let tempVal = val.format("YYYY-MM-DD")
        function isDateInRange(dateToCheck, startDate, endDate) {
          return  new Date(dateToCheck) >= new Date(startDate) && new Date(dateToCheck) <= new Date(endDate);
        }
        let bool =  isDateInRange(tempVal,sdate.value,edate.value)
        if(bool){
          _className = 'normal'
        }else{
          _className = 'invalid'
        }
      return _className;
    }

    const dateval = ref();
    const departmentId = ref();
    const showM = async (val)=>{
     // console.log( val.format("YYYY-MM-DD"))
      dateval.value = val.format("YYYY-MM-DD");
      let form = await validate();
      departmentId.value = form.departmentId;
      console.log(dateval.value)

      openModal(true,{dateval:dateval.value,departmentId:departmentId.value});


    }

    const date = ref();
    const onPanelChange = (a) => {
      console.log(a);
    };
    const selectDate = (val) => {
      console.log(val);
      date.value = val;
    };
    // 自定义日历头
    const format = (val) => {
      const newVal = dayjs(val).format("YYYY-MM");
      console.log(val, newVal);
      return newVal;
    };

    onMounted(()=>{
      console.log(111);
      console.log(date);
      // getDateArr()
    })

function getMonthFirst() {

      function doHandleMonth(month) {
          var m = month;
          if (month.toString().length == 1) {
              m = "0" + month;
          }
          return m;
      }
      var today = new Date();
      // var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
      // today.setTime(targetday_milliseconds); //注意，这行是关键代码
      var tYear = today.getFullYear();
      var tMonth = today.getMonth();
      var tDate = today.getDate();
      tMonth = doHandleMonth(tMonth + 1);
      tDate = doHandleMonth(tDate);
      return tYear + "-" + tMonth + "-" + tDate;
}
 function getMonthLast() {
    function doHandleMonth(month) {
          var m = month;
          if (month.toString().length == 1) {
              m = "0" + month;
          }
          return m;
      }
      function getLastDayOfMonth(year, month) {
        const lastDay = new Date(year, month, 0).getDate();
        return lastDay;
      }
      var today = new Date();
      var tYear = today.getFullYear();
      var tMonth = today.getMonth();
      tMonth = doHandleMonth(tMonth + 1);
      let monthLastDate = getLastDayOfMonth(tYear,tMonth)
      console.log(1111);
      console.log(monthLastDate);
      return tYear + "-" + tMonth + "-" + monthLastDate
}
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}

  .buttonRow{
    display: flex;
    justify-content: center;
  }

  .box {
    .header {
      padding: 12px;
      text-align: center;
    }
    .date {
      position: relative;
      z-index: 2;
      display: inline-block;
      min-width: 24px;
      height: 24px;
      line-height: 24px;
      border-radius: 2px;
      transition: background 0.3s, border 0.3s;
      &.work {
        background-color: rgb(20, 134, 228);
      }
      &.week {
        background-color: rgb(193, 240, 97);
      }
    }
  }
  .red{
    color: #f56f6f;
  }

  .normal{
    color: #000;
  }
  .invalid{
    color: #e5e7eb;
  }
  /deep/.ant-radio-group .ant-radio-group-outline .ant-radio-group-small .ant-picker-calendar-mode-switch{
      display: none !important;
  }
 
 
</style>
